﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
using Ls.Utils;
using Ls.Web.Api.Models;
using Ls.Web.Framework;
using Ls.Web.Framework.Jwt;
using Ls.Web.Framework.Permissions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace Ls.Web.Api.Controllers
{
    /// <summary>
    /// 仓库管理相关接口
    /// </summary>
    public class WhController : BaseController
    {
        WhInventoryBarcodeService whInventoryBarcodeService = new WhInventoryBarcodeService();
        WhInventoryBarcodeBookService whInventoryBarcodeBookService = new WhInventoryBarcodeBookService();
        WhInventoryService whInventoryService = new WhInventoryService();
        WhInventoryBookService whInventoryBookService = new WhInventoryBookService();
        WhBatteryService whBatteryService = new WhBatteryService();
        WhBatteryBookService whBatteryBookService = new WhBatteryBookService();

        WhProduct2BatteryService whProduct2BatteryService = new WhProduct2BatteryService();
        CusCustomerService cusCustomerService = new CusCustomerService();
        SysMessageService sysMessageService = new SysMessageService();

        FncAccountService fncAccountService = new FncAccountService();

        /// <summary>
        /// 整车条码查询（含电池）
        /// </summary>
        /// <param name="product_barcode">整车条码</param>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///     {
        ///         "resultCode": 接口返回状态,
        ///         "data": {
        ///             "product_barcode": 整车条码,
        ///             "product_code": 车型编码,
        ///             "product_prefixname": 车型名称,
        ///             "product_color": 颜色,
        ///             "wh_id": 仓库编号,
        ///             "wh_name": 仓库名称,
        ///             "whib_status": 库存状态：0 在库,1 在途,2 已售出,
        ///             "time": 当前时间（精确到秒，格式为：yyyy-MM-dd HH:mm:ss）,
        ///             "battery": [
        ///                 {
        ///                     "battery_code": 电池编码,
        ///                     "battery_name": 电池名称,
        ///                     "battery_spec": 电池规格,
        ///                     "whb_cfg_type": 电池配置类型：0 标配,1 换配
        ///                 }
        ///             ]
        ///         }
        ///     }
        /// </remarks>
        [HttpPost]
        [Route("/wh/productinfo")]
        [Permission("App.Product.Info")]
        public IActionResult ProductInfo(string product_barcode)
        {
            try
            {
                dynamic wh_id = UserInfo.whId;
                dynamic wh_name = UserInfo.whName;

                object where = new
                {
                    product_barcode = product_barcode.Replace("'", "''"),
                    wh_id = wh_id,
                };
                dynamic product_info;

                product_info = whInventoryBarcodeService.Single("product_barcode, product_code, product_prefixname, product_color, wh_id, wh_name, whib_status ", where);

                string product_code = Convert.ToString(product_info.product_code);

                where = new
                {
                    product_code = product_code.Substring(0, 5) + "00" + product_code.Substring(7, 2),
                    whb_status = 0
                };

                dynamic battery_info = whProduct2BatteryService.GetList<dynamic>(where, "battery_code, battery_name, battery_spec, whb_cfg_type", "whb_cfg_type,battery_code");

                List<object> batterylist = new List<object>();

                foreach (dynamic battery in battery_info)
                {
                    dynamic batteryinfo = new
                    {
                        battery_code = battery.battery_code,
                        battery_name = battery.battery_name,
                        battery_spec = battery.battery_spec,
                        whb_cfg_type = battery.whb_cfg_type
                    };
                    batterylist.Add(batteryinfo);
                }

                return GetSuccessResult(new
                {
                    product_barcode = product_info.product_barcode,
                    product_code = product_info.product_code,
                    product_prefixname = product_info.product_prefixname,
                    product_color = product_info.product_color,
                    wh_id = product_info.wh_id,
                    wh_name = product_info.wh_name,
                    whib_status = product_info.whib_status,
                    time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    battery = batterylist
                });
            }
            catch (Exception exception)
            {
                if (exception.Message.IndexOf("Cannot perform runtime binding on a null reference") > -1)
                {
                    return GetErrorResult("条码错误或该条码不在您的门店！");
                }
                else
                {
                    return GetErrorResult(exception.Message);
                }
            }
        }

        /// <summary>
        /// 库存电池查询
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///     {
        ///         "resultCode": 接口返回状态,
        ///         "data": {
        ///             "wh_id": 仓库编号,
        ///             "wh_name": 仓库名称,
        ///             "time": 当前时间（精确到秒，格式为：yyyy-MM-dd HH:mm:ss）,
        ///             "battery": [
        ///                 {
        ///                     "battery_code": 电池编码,
        ///                     "battery_name": 电池名称,
        ///                     "battery_spec": 电池规格,
        ///                     "whb_amount": 电池在库数量（可售数量）
        ///                 }
        ///             ]
        ///         }
        ///     }
        /// </remarks>
        [HttpPost]
        [Route("/wh/batterylist")]
        [Permission("App.Product.Info")]
        public IActionResult BatteryList()
        {
            try
            {
                dynamic wh_id = UserInfo.whId;
                dynamic wh_name = UserInfo.whName;

                string where = "wh_id = " + Convert.ToString(wh_id) + " and whb_amount > 0";

                dynamic battery_info = whBatteryService.GetList<dynamic>(where, "battery_code, battery_name, battery_spec, whb_amount", "battery_code");

                List<object> batterylist = new List<object>();

                foreach (dynamic battery in battery_info)
                {
                    dynamic batteryinfo = new
                    {
                        battery_code = battery.battery_code,
                        battery_name = battery.battery_name,
                        battery_spec = battery.battery_spec,
                        whb_amount = battery.whb_amount
                    };
                    batterylist.Add(batteryinfo);
                }

                return GetSuccessResult(new
                {
                    wh_id = wh_id,
                    wh_name = wh_name,
                    time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    battery = batterylist
                });
            }
            catch (Exception exception)
            {
                return GetErrorResult(exception.Message);
            }
        }

        /// <summary>
        /// 零售确认销售
        /// </summary>
        /// <param name="cus_name">用户姓名</param>
        /// <param name="cus_phone">联系电话</param>
        /// <param name="cus_idcard">身份证号（选填）</param>
        /// <param name="price_retail_product">整车零售价格</param>
        /// <param name="price_retail_battery">电池零售价格</param>
        /// <param name="cus_amount_battery">电池组数</param>
        /// <param name="product_barcode">整车条码</param>
        /// <param name="battery_code">电池编码</param>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///     {
        ///         "resultCode": "200", //状态
        ///         "info": "销售确认成功！", //信息
        ///     }
        /// </remarks>
        [HttpPost]
        [Route("/wh/saleordersubmit")]
        [Permission("App.Product.Submit")]
        public IActionResult SaleOrderSubmit(string cus_name, string cus_phone, string cus_idcard, int price_retail_product, int price_retail_battery, int cus_amount_battery, string product_barcode = "", string battery_code = "")
        {
            if (product_barcode.IsNullOrEmpty() && battery_code.IsNullOrEmpty())
            {
                return GetErrorResult("未检测到产品信息，请输入！");
            }
            else
            {
                try
                {
                    long wh_id = UserInfo.whId;
                    string wh_name = UserInfo.whName;
                    long store_id = UserInfo.storeId;
                    string store_name = UserInfo.storeName;
                    string store_code = UserInfo.storeCode;

                    string product_code = "";
                    string product_prefixname = "";
                    string product_color = "";
                    string battery_name = "";
                    string battery_spec = "";
                    int price_sale_product = 0;
                    int price_sale_battery = 0;
                    int amount_order = 0;

                    //获取电池和整车信息（含价格）
                    dynamic product_barcode_info;
                    dynamic product_price_info;
                    dynamic battery_price_info;

                    List<dynamic> sqlList = new List<dynamic>();

                    string cus_order = cusCustomerService.GetCode("cus_order", "XS", 8);

                    //条码不为空，则判断整车仓库归属
                    if (!product_barcode.IsNullOrEmpty())
                    {
                        object where_product = new
                        {
                            product_barcode = product_barcode.Replace("'", "''"),
                            wh_id = wh_id,  //当前仓库
                            whib_status = 0, //在库
                        };

                        product_barcode_info = whInventoryBarcodeService.Single("product_code, product_prefixname, product_color,whi_id,wh_id,wh_name,whib_status", where_product);

                        if (product_barcode_info == null)
                        {
                            return GetErrorResult("该条码状态异常，或者已售出！");
                        }
                        else
                        {
                            product_code = product_barcode_info.product_code;
                            product_prefixname = product_barcode_info.product_prefixname;
                            product_color = product_barcode_info.product_color;

                            dynamic product_barcode_update_parameter = new
                            {
                                //whi_id = 0,
                                //wh_id = 0,
                                //wh_name = "", //不更新门店信息可以方便后期统计门店销量
                                order_code = cus_order,
                                whib_status = 2,
                                update_id = UserInfo.userId,
                                update_time = DateTime.Now,
                            };

                            dynamic product_barcode_update_where = new
                            {
                                product_barcode = product_barcode
                            };

                            dynamic product_barcode_book_insert_parameter = new
                            {
                                product_barcode = product_barcode,
                                product_code = product_code,
                                product_prefixname = product_prefixname,
                                product_color = product_color,
                                order_code = cus_order,
                                whibb_type = "销售确认",
                                whi_id_before = (long)product_barcode_info.whi_id,
                                whi_id_after = (long)product_barcode_info.whi_id,
                                wh_id_before = (long)product_barcode_info.wh_id,
                                wh_id_after = (long)product_barcode_info.wh_id,
                                wh_name_before = (string)product_barcode_info.wh_name,
                                wh_name_after = (string)product_barcode_info.wh_name,
                                whibb_status_before = (int)product_barcode_info.whib_status,
                                whibb_status_after = 2,
                                create_id = UserInfo.userId,
                                create_time = DateTime.Now
                            };

                            sqlList.Add(new { parameter = product_barcode_update_parameter, where = product_barcode_update_where, sqlType = WhInventoryService.sqlType.update, tablename = "wh_inventory_barcode" });
                            sqlList.Add(new { parameter = product_barcode_book_insert_parameter, sqlType = WhInventoryService.sqlType.insert, tablename = "wh_inventory_barcode_book" });

                            string sql = @"select a.whi_id,a.wh_id,a.wh_name,a.whi_amount_trans,a.product_code,a.whi_amount,b.fncpr_price
                            from wh_inventory a 
                            inner join fnc_price_retail b
                                on concat(left(a.product_code,5),'00',right(a.product_code,2)) = b.fncpr_code
                            where a.wh_id = @wh_id 
                            and b.from_id = @from_id
                            and a.product_code = @product_code";

                            product_price_info = db.Sql(sql).Parameter("wh_id", wh_id).Parameter("from_id", UserInfo.carrierId).Parameter("product_code", product_code).QuerySingle<dynamic>();

                            if (product_price_info == null)
                            {
                                return GetErrorResult("仓库整车库存信息错误，请检查库存信息！");
                            }
                            else
                            {
                                if (product_price_info.whi_amount > 0)
                                {
                                    if (product_price_info.fncpr_price > 0)
                                    {
                                        dynamic product_update_parameter = new
                                        {
                                            whi_amount = (int)product_price_info.whi_amount - 1,
                                        };

                                        dynamic product_update_where = new
                                        {
                                            wh_id = UserInfo.whId,
                                            product_code = product_code
                                        };

                                        dynamic product_book_insert_parameter = new
                                        {
                                            whi_id = (long)product_price_info.whi_id,
                                            wh_id = (long)product_price_info.wh_id,
                                            wh_name = (string)product_price_info.wh_name,
                                            order_code = cus_order,
                                            product_code = product_code,
                                            product_prefixname = product_prefixname,
                                            product_color = product_color,
                                            whib_type = "销售确认",
                                            whib_amount_before = (int)product_price_info.whi_amount,
                                            whib_amount_occur = -1,
                                            whib_amount_after = (int)product_price_info.whi_amount - 1,
                                            whib_amount_trans_before = (int)product_price_info.whi_amount_trans,
                                            whib_amount_trans_occur = 0,
                                            whib_amount_trans_after = (int)product_price_info.whi_amount_trans,
                                            create_id = UserInfo.userId,
                                            create_time = DateTime.Now
                                        };

                                        sqlList.Add(new { parameter = product_update_parameter, where = product_update_where, sqlType = WhInventoryService.sqlType.update, tablename = "wh_inventory" });
                                        sqlList.Add(new { parameter = product_book_insert_parameter, sqlType = WhInventoryService.sqlType.insert, tablename = "wh_inventory_book" });

                                        price_sale_product = product_price_info.fncpr_price;
                                    }
                                    else
                                    {
                                        return GetErrorResult("整车价格设置错误！");
                                    }
                                }
                                else
                                {
                                    return GetErrorResult("整车库存不足！");
                                }
                            }
                        }
                    }

                    if (!battery_code.IsNullOrEmpty() && cus_amount_battery > 0)
                    {

                        string sql = @"select a.battery_code,a.battery_name,a.battery_spec,a.whb_amount,whb_amount_trans,b.fncpr_price,a.whb_id,a.wh_id,a.wh_name,a.battery_amount
                            from wh_battery a 
                            inner join fnc_price_retail b
                                on a.battery_code = b.fncpr_code
                            where a.wh_id = @wh_id 
                            and b.from_id = @from_id
                            and a.battery_code = @battery_code";

                        battery_price_info = db.Sql(sql).Parameter("wh_id", wh_id).Parameter("from_id", UserInfo.carrierId).Parameter("battery_code", battery_code).QuerySingle<dynamic>();

                        if (battery_price_info == null)
                        {
                            return GetErrorResult("仓库电池库存信息错误，请检查库存信息！");
                        }
                        else
                        {
                            if (battery_price_info.whb_amount >= cus_amount_battery)
                            {
                                if (battery_price_info.fncpr_price > 0)
                                {
                                    battery_name = battery_price_info.battery_name;
                                    battery_spec = battery_price_info.battery_spec;

                                    dynamic battery_update_parameter = new
                                    {
                                        whb_amount = (int)battery_price_info.whb_amount - cus_amount_battery,
                                    };

                                    dynamic battery_update_where = new
                                    {
                                        wh_id = UserInfo.whId,
                                        battery_code = battery_code
                                    };

                                    dynamic battery_book_insert_parameter = new
                                    {
                                        whb_id = (long)battery_price_info.whb_id,
                                        wh_id = (long)battery_price_info.wh_id,
                                        wh_name = (string)battery_price_info.wh_name,
                                        order_code = cus_order,
                                        battery_code = battery_code,
                                        battery_name = battery_name,
                                        battery_spec = battery_spec,
                                        whbb_type = "销售确认",
                                        battery_amount = (int)battery_price_info.battery_amount,
                                        whbb_amount_before = (int)battery_price_info.whb_amount,
                                        whbb_amount_occur = -cus_amount_battery,
                                        whbb_amount_after = (int)battery_price_info.whb_amount - cus_amount_battery,
                                        whbb_amount_trans_before = (int)battery_price_info.whb_amount_trans,
                                        whbb_amount_trans_occur = 0,
                                        whbb_amount_trans_after = (int)battery_price_info.whb_amount_trans,
                                        create_id = UserInfo.userId,
                                        create_time = DateTime.Now
                                    };

                                    sqlList.Add(new { parameter = battery_update_parameter, where = battery_update_where, sqlType = WhInventoryService.sqlType.update, tablename = "wh_battery" });
                                    sqlList.Add(new { parameter = battery_book_insert_parameter, sqlType = WhInventoryService.sqlType.insert, tablename = "wh_battery_book" });

                                    price_sale_product = battery_price_info.fncpr_price;
                                }
                                else
                                {
                                    return GetErrorResult("电池价格设置错误！");
                                }
                            }
                            else
                            {
                                return GetErrorResult("电池库存不足！");
                            }
                        }
                    }

                    dynamic customer_insert_parameter = new
                    {
                        cus_order = cus_order,
                        cus_name = cus_name,
                        cus_phone = cus_phone,
                        cus_idcard = cus_idcard,
                        buy_time = DateTime.Now,
                        product_barcode = product_barcode,
                        product_code = product_code,
                        product_prefixname = product_prefixname,
                        product_color = product_color,
                        battery_code = battery_code,
                        battery_name = battery_name,
                        battery_spec = battery_spec,
                        cus_amount_battery = cus_amount_battery,
                        price_retail_product = price_retail_product,
                        price_sale_product = price_sale_product,
                        price_retail_battery = price_retail_battery,
                        price_sale_battery = price_sale_battery,
                        store_id = store_id,
                        store_name = store_name,
                        store_code = store_code,
                        cus_status = 0,
                        create_id = UserInfo.userId,
                        create_time = DateTime.Now,
                        update_id = UserInfo.userId,
                        update_time = DateTime.Now
                    };

                    sqlList.Add(new { parameter = customer_insert_parameter, sqlType = WhInventoryService.sqlType.insert, tablename = "cus_customer" });

                    amount_order = price_retail_product + price_retail_battery * cus_amount_battery;

                    dynamic account_info = fncAccountService.Single("fnca_id,carrier_id,carrier_code,carrier_name,store_id,store_code,store_name,account_receivable", new
                    {
                        carrier_id = UserInfo.carrierId,
                        store_id = UserInfo.storeId
                    });

                    dynamic account_update_parameter = new
                    {
                        account_receivable = (int)account_info.account_receivable + amount_order,
                        update_id = UserInfo.userId,
                        update_time = DateTime.Now
                    };

                    dynamic account_update_where = new
                    {
                        fnca_id = (long)account_info.fnca_id,
                    };

                    dynamic account_book_insert_parameter = new
                    {
                        fnca_id = (long)account_info.fnca_id,
                        carrier_id = (long)account_info.carrier_id,
                        carrier_code = (string)account_info.carrier_code,
                        carrier_name = (string)account_info.carrier_name,
                        store_id = (long)account_info.store_id,
                        store_code = (string)account_info.store_code,
                        store_name = (string)account_info.store_name,
                        fncab_order = cus_order,
                        fncab_type = "销售确认",
                        amount_begin = (int)account_info.account_receivable,
                        amount_receivable = amount_order,
                        amount_received = 0,
                        amount_end = (int)account_info.account_receivable + amount_order,
                        create_id = UserInfo.userId,
                        create_time = DateTime.Now
                    };

                    sqlList.Add(new { parameter = account_update_parameter, where = account_update_where, sqlType = WhInventoryService.sqlType.update, tablename = "fnc_account" });
                    sqlList.Add(new { parameter = account_book_insert_parameter, sqlType = WhInventoryService.sqlType.insert, tablename = "fnc_account_book" });

                    int ret = whInventoryService.ExecTranSql(sqlList);

                    return GetSuccessResult("销售确认成功！");
                }
                catch (Exception exception)
                {
                    return GetErrorResult(exception.Message);
                }

            }
        }

        /// <summary>
        /// 获取新消息数量
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///     {
        ///         "resultCode": 接口返回状态,
        ///         "data": {
        ///             "user_id": 用户id,
        ///             "count": 新消息数量
        ///         }
        ///     }
        /// </remarks>
        [HttpPost]
        [Route("/wh/messagecount")]
        [Permission("App.Message.Info")]
        public IActionResult MessageCount()
        {
            try
            {
                object where = new
                {
                    user_id = UserInfo.userId,
                    sysm_status = 0,
                };

                dynamic message_count = sysMessageService.Single("count(1) as count ", where);

                return GetSuccessResult(new
                {
                    user_id = UserInfo.userId,
                    count = message_count.count
                });
            }
            catch (Exception exception)
            {
                return GetErrorResult(exception.Message);
            }
        }

        /// <summary>
        /// 获取消息数据（同时更新消息状态）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">单页数量</param>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///     {
        ///         "resultCode": 接口返回状态,
        ///         "data": {
        ///             "user_id": 用户id,
        ///             "sysm_type": 消息类型：0 调拨单,1 销售单,2 其他（待扩展）
        ///             "sysm_message": 消息内容：内部为json格式的string，需要前端自行解析
        ///             "sysm_status": 消息状态：0 未读,1 已读
        ///             "create_time": 消息发出时间
        ///         }
        ///     }
        /// </remarks>
        [HttpPost]
        [Route("/wh/getmessage")]
        [Permission("App.Message.Info")]
        public IActionResult GetMessage(int pageIndex, int pageSize)
        {
            try
            {
                string where = "user_id = " + Convert.ToString(UserInfo.userId) + " and sysm_is_del = 0 ";

                dynamic message_list = sysMessageService.Page("user_id,sysm_type, sysm_message, sysm_status, create_time", where, "sysm_status,create_time desc");

                sysMessageService.UpdateWithUser(new { sysm_status = 1,sysm_is_del = 0 }, new { user_id = UserInfo.userId });

                return Json(message_list);
            }
            catch (Exception exception)
            {
                return GetErrorResult(exception.Message);
            }
        }
    }
}